<template>
  <view class="solve-list-page">
    <Navbar title="告警记录" />

    <!-- 筛选区域 -->
    <view class="filter-group">
      <!-- 时间选择器 -->
      <view class="filter-item">
        <view class="filter-label">时间</view>
        <view class="filter-input" @click="showCalendar = true">
          <image
            src="/static/img/consolePages/date-filter.png"
            class="filter-icon"
            mode="widthFix"
          ></image>
          <view class="filter-text">{{ timeDisplay || '选择时间' }}</view>
        </view>
      </view>

      <!-- 区域选择器 -->
      <tn-picker
        v-model:open="showAreaPicker"
        :data="areaPickerData"
        :model-value="areaValue"
        :immediate-change="false"
        :mask="true"
        :show-cancel="false"
        confirm-color="#1ec8e1"
        label-key="label"
        value-key="value"
        @confirm="onAreaConfirm"
      />
      <view class="filter-item">
        <view class="filter-label">区域</view>
        <view class="filter-input" @click="showAreaPicker = true">
          <image
            src="/static/img/consolePages/area-filter.png"
            class="filter-icon"
            mode="widthFix"
          ></image>
          <view class="filter-text">{{ areaDisplay || '选择区域' }}</view>
        </view>
      </view>
    </view>

    <!-- 告警列表 -->
    <view class="alarm-list">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <view class="loading-text">加载中...</view>
      </view>

      <!-- 空状态 -->
      <view v-else-if="solveList.length === 0" class="empty-container">
        <view class="empty-text">暂无告警记录</view>
      </view>

      <!-- 告警列表 -->
      <view
        v-else
        class="alarm-item"
        v-for="item in solveList"
        :key="item.id"
        @click="mygo('/pages/consolePages/recordDetail', { id: item.id })"
      >
        <view class="alarm-content">
          <view class="device-name">{{ item.monitorDeviceName }}</view>
          <view class="alarm-time">{{ item.alertTime }}</view>
          <view
            :class="[
              'status-badge',
              `status-${getStatusClass(item.alertStatus)}`,
            ]"
          >
            {{ item.alertStatus }}
          </view>
        </view>
        <!-- 四个角落装饰 -->
        <image
          class="left-bottom"
          src="/static/img/left-bottom.png"
          mode="widthFix"
        ></image>
        <image
          class="right-bottom"
          src="/static/img/right-bottom.png"
          mode="widthFix"
        ></image>
        <image
          class="left-top"
          src="/static/img/left-top.png"
          mode="widthFix"
        ></image>
        <image
          class="right-top"
          src="/static/img/right-top.png"
          mode="widthFix"
        ></image>
      </view>
    </view>

    <!-- 时间选择器（日历） -->
    <tn-popup
      v-model="showCalendar"
      open-direction="bottom"
      :custom-style="{ borderRadius: '32rpx 32rpx 0 0' }"
    >
      <tn-calendar
        v-model="selectDate"
        mode="range"
        active-bg-color="#1ec8e1"
        active-text-color="#fff"
        range-bg-color="#3284d1"
        range-text-color="#84d132"
        range-start-desc="开始"
        range-end-desc="结束"
        min-date="2024-10-18"
        :max-date="maxDate"
        class="console-calendar"
      />
    </tn-popup>
  </view>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { useAreaStore } from '@/store/area';
import { useAreaPickerStore } from '@/store/areaPicker';
import { mygo } from '@/utils/useNavigator';
import { createRequest } from '@/utils/request';
import Navbar from '@/components/Navbar.vue';

// 获取store实例
const areaStore = useAreaStore();
const areaPickerStore = useAreaPickerStore();

// 响应式数据
const showCalendar = ref(false);
const showAreaPicker = ref(false);
const selectDate = ref([]);
const areaValue = ref('');
const solveList = ref([]);
const loading = ref(false);

// 计算属性
const timeDisplay = computed(() => {
  if (selectDate.value && selectDate.value.length === 2) {
    const start = selectDate.value[0];
    const end = selectDate.value[1];
    if (start && end) {
      return `${start} 至 ${end}`;
    }
  }
  return '';
});

const areaDisplay = computed(() => {
  if (areaValue.value) {
    return areaStore.getAreaDisplayByValue([areaValue.value]);
  }
  return '';
});

const maxDate = computed(() => {
  const today = new Date();
  return today.toISOString().split('T')[0];
});

const areaPickerData = computed(() => {
  return areaPickerStore.getAreaPickerData();
});

// 方法
const fetchSolveList = async () => {
  loading.value = true;
  try {
    // 检查日期参数是否有效
    const hasValidDate =
      selectDate.value &&
      selectDate.value.length === 2 &&
      selectDate.value[0] &&
      selectDate.value[1];

    // 将斜杠格式转换为连字符格式，用于API请求
    const formatDateForAPI = dateStr => {
      return dateStr.replace(/\//g, '-');
    };

    // 格式化时间参数，参考detail页面的处理方式
    const startTime = hasValidDate
      ? encodeURIComponent(formatDateForAPI(selectDate.value[0]) + 'T00:00:00')
      : '';
    const endTime = hasValidDate
      ? encodeURIComponent(formatDateForAPI(selectDate.value[1]) + 'T23:59:59')
      : '';

    const result = await createRequest(
      `/alert/getRangeAlertList?regionId=${areaValue.value}&startTime=${startTime}&endTime=${endTime}`
    );

    if (result.code === 200 && result.data) {
      solveList.value = result.data;
    } else {
      solveList.value = [];
    }
  } catch (error) {
    console.error('获取告警列表失败:', error);
    uni.showToast({
      title: '获取数据失败',
      icon: 'none',
    });
    solveList.value = [];
  } finally {
    loading.value = false;
  }
};

const onAreaConfirm = value => {
  areaValue.value = value;
  fetchSolveList();
};

// 监听日历关闭事件，触发数据请求
watch(showCalendar, (newVal, oldVal) => {
  if (oldVal && !newVal) {
    // 日历关闭时触发数据请求
    fetchSolveList();
  }
});

const getStatusClass = status => {
  switch (status) {
    case '待确认':
      return 'processing';
    case '待处理':
      return 'processing';
    case '待审核':
      return 'reviewing';
    case '已结束':
      return 'completed';
    default:
      return 'default';
  }
};

// 解析URL参数
const parseUrlParams = options => {
  if (options.area) {
    try {
      areaValue.value = decodeURIComponent(options.area) || '';
    } catch (error) {
      console.error('解析区域参数失败:', error);
    }
  }

  if (options.date) {
    try {
      const dateParam = decodeURIComponent(options.date);
      // 统一日期格式为斜杠格式
      const normalizeDate = dateStr => {
        return dateStr.replace(/-/g, '/');
      };

      if (dateParam.includes(',')) {
        // 处理日期范围
        const dateArray = dateParam.split(',');
        selectDate.value = dateArray.map(date => normalizeDate(date.trim()));
      } else {
        // 处理单个日期
        selectDate.value = [normalizeDate(dateParam.trim())];
      }
    } catch (error) {
      console.error('解析日期参数失败:', error);
    }
  }
};

// 生命周期
onLoad(options => {
  parseUrlParams(options);
  fetchSolveList();
});
</script>

<style scoped lang="scss">
.solve-list-page {
  @include page-with-header;
  background: #0a1e4a;
  min-height: 100vh;
}

.filter-group {
  display: flex;
  flex-direction: column;
  padding: 30rpx 30rpx 20rpx;
  gap: 20rpx;
}

.filter-item {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  gap: 30rpx;
}

.filter-label {
  font-size: 26rpx;
  color: #fff;
  text-align: left;
  min-width: 60rpx;
}

.filter-input {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  border-radius: 8rpx;
  background-color: rgba(255, 255, 255, 0.08);
  transition: all 0.3s ease;
  width: 100%;
  height: 60rpx;
  color: #fff;
  padding: 0 20rpx;
  box-sizing: border-box;
  border: 1rpx solid rgba(43, 149, 229, 0.3);
}

.filter-input:active {
  transform: scale(0.98);
  background-color: rgba(30, 200, 225, 0.15);
  border-color: #1ec8e1;
}

.filter-icon {
  width: 28rpx;
  height: 28rpx;
  margin-right: 12rpx;
}

.filter-text {
  font-size: 26rpx;
  color: #fff;
  line-height: 1.2;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.console-calendar {
  box-sizing: border-box;
  color: #eee;
}

:deep(.tn-popup__content) {
  background-color: #1f3462 !important;
}

:deep(.uni-picker-view-mask) {
  background: transparent !important;
}

:deep(.tn-calendar__data) {
  box-sizing: border-box !important;
}

:deep(.tn-calendar__week-text) {
  box-sizing: border-box !important;
}

:deep(.tn-calendar__operation) {
  box-sizing: border-box !important;
}

.alarm-list {
  padding: 0 30rpx 30rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.loading-container,
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  gap: 20rpx;
}

.loading-text,
.empty-text {
  font-size: 28rpx;
  color: #b0b8c8;
  text-align: center;
}

.alarm-item {
  background: linear-gradient(135deg, #1a2a4a 0%, #162238 100%);
  border: 2rpx solid #2b95e5;
  border-radius: 8rpx;
  padding: 24rpx 28rpx;
  transition: all 0.3s ease;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.3),
    0 0 0 1rpx rgba(43, 149, 229, 0.2), inset 0 1rpx 0 rgba(255, 255, 255, 0.05);
  position: relative;
}

.alarm-item::before {
  content: '';
  position: absolute;
  top: -1rpx;
  left: -1rpx;
  right: -1rpx;
  bottom: -1rpx;
  background: linear-gradient(135deg, #2b95e5, #1ec8e1);
  border-radius: 8rpx;
  z-index: -1;
  opacity: 0.3;
  filter: blur(2rpx);
}

.alarm-item:active {
  background: linear-gradient(135deg, #2a3a5a 0%, #1e2e4a 100%);
  border-color: #1ec8e1;
  transform: scale(0.98);
  box-shadow: 0 6rpx 16rpx rgba(30, 200, 225, 0.3),
    0 0 0 2rpx rgba(30, 200, 225, 0.4), inset 0 1rpx 0 rgba(255, 255, 255, 0.1);
}

// 四个角落装饰样式
.left-bottom,
.right-bottom,
.left-top,
.right-top {
  position: absolute;
  width: 16rpx;
  height: 16rpx;
  z-index: 1;
}

.left-bottom {
  left: -1rpx;
  bottom: -1rpx;
}

.right-bottom {
  right: -1rpx;
  bottom: -1rpx;
}

.left-top {
  left: -1rpx;
  top: -1rpx;
}

.right-top {
  right: -1rpx;
  top: -1rpx;
}

.alarm-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 24rpx;
  width: 100%;
}

.device-name {
  font-size: 28rpx;
  color: #fff;
  font-weight: 500;
  flex: 1;
  text-align: left;
  min-width: 0;
}

.alarm-time {
  font-size: 24rpx;
  color: #b0b8c8;
  flex: 1;
  text-align: center;
  min-width: 0;
}

.status-badge {
  padding: 8rpx 16rpx;
  border-radius: 4rpx;
  font-size: 22rpx;
  font-weight: 500;
  color: #fff;
  min-width: 80rpx;
  text-align: center;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
  flex-shrink: 0;
  border: 1rpx solid rgba(255, 255, 255, 0.1);
}

.status-processing {
  background: #ff871e;
  box-shadow: 0 2rpx 6rpx rgba(255, 135, 30, 0.4);
}

.status-reviewing {
  background: #ffb74d;
  box-shadow: 0 2rpx 6rpx rgba(255, 183, 77, 0.4);
}

.status-completed {
  background: #04fbf8;
  color: #1a1a1a;
  font-weight: 600;
  box-shadow: 0 2rpx 6rpx rgba(4, 251, 248, 0.4);
}

.status-default {
  background: #747d8c;
  box-shadow: 0 2rpx 6rpx rgba(116, 125, 140, 0.4);
}
</style>
